import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { jwtConstants } from '../../../constants/jwt.constant';
import { DrizzleService } from '../../../db/drizzle.service';
import { users } from '../../../db/schema';
import { eq, and } from 'drizzle-orm';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly drizzle: DrizzleService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    // 在这里可以根据payload中的信息查询用户
    const { sub: userId } = payload;

    // 查询用户信息
    const userResult = await this.drizzle.db
      .select({
        userId: users.userId,
        userName: users.userName,
        nickName: users.nickName,
        email: users.email,
        status: users.status,
        deptId: users.deptId
      })
      .from(users)
      .where(
        and(
          eq(users.userId, userId),
          eq(users.status, '0'),  // 0-正常状态
          eq(users.delFlag, '0')  // 0-未删除
        )
      );

    if (!userResult || userResult.length === 0) {
      throw new UnauthorizedException('用户不存在或已被禁用');
    }

    return userResult[0]; // 返回的对象将被添加到请求对象中，可在控制器中通过@Request() req获取
  }
} 